﻿/*	
	stencil - action script 3 isometric game engine.

	http://code.google.com/p/stencilas3/
	
	Copyright (c) 2010 Max Zhuravkov, All Rights Reserved.

	Permission is hereby granted, free of charge, to any person obtaining a copy of
	this software and associated documentation files (the "Software"), to deal in
	the Software without restriction, including without limitation the rights to
	use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies
	of the Software, and to permit persons to whom the Software is furnished to do
	so, subject to the following conditions:

	The above copyright notice and this permission notice shall be included in all
	copies or substantial portions of the Software.

	THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
	IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
	FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
	AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
	LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
	OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
	SOFTWARE.
*/
package stencil.core.engine {

	import flash.display.Sprite;
	import flash.geom.Point;
	import flash.geom.Rectangle;
	import flash.text.TextField;
	import stencil.core.engine.Position;
	import stencil.core.errors.ArgumentIsNullError;
	
	/**
	 * Isometric grid.
	 * 
	 * @author	Max Zhuravkov
	 */
	public class IsometricGrid implements IGrid {
		
		private var _cellWidth:Number;
		
		private var _cellHeight:Number;
		
		private var _halfCellWidth:Number;
		
		private var _halfCellHeight:Number;
		
		private var _offset:Point;
		
		private var _globalOffset:Point;
		
		//------------------------------------------------------------------------------------------------
		// Constructor
		//------------------------------------------------------------------------------------------------
		
		public function IsometricGrid(cellWidth:Number = 60, cellHeight:Number = 30) {
			this.cellWidth = cellWidth;
			this.cellHeight = cellHeight;
		}
		
		//------------------------------------------------------------------------------------------------
		// Public methods
		//------------------------------------------------------------------------------------------------
		
		/**
		 * @inheritDoc
		 */
		public function set cellWidth(value:Number):void {
			if (value <= 0) {
				throw new ArgumentError("cellWidth should be greater then 0.");
			}
			if (this._cellWidth == value) {
				return;
			}
			this._cellWidth = value;
			this._halfCellWidth = value / 2;
			
		}
		 
		public function get cellWidth():Number {
			return this._cellWidth;
		}
		
		/**
		 * @inheritDoc
		 */
		public function set cellHeight(value:Number):void {
			if (value <= 0) {
				throw new ArgumentError("cellWidth should be greater then 0.");
			}
			if (this._cellHeight == value) {
				return;
			}
			this._cellHeight = value;
			this._halfCellHeight = value / 2;
		}
		
		public function get cellHeight():Number {
			return this._cellHeight;
		}
		
		/**
		 * @inheritDoc
		 */
		public function get offset():Point {
			return this._offset;
		}
		
		/**
		 * @inheritDoc
		 */
		public function get globalOffset():Point {
			return this._globalOffset;
		}
		
		//------------------------------------------------------------------------------------------------
		// Public methods
		//------------------------------------------------------------------------------------------------
		
		/**
		 * @inheritDoc
		 */
		public function redraw(cells:Array, container:Sprite, absolutePositions:Boolean = false):void {
			
			if (!absolutePositions) {
				var offset:MapNode = cells[0];
				
				for each(var c:MapNode in cells) {
					if (offset.x >= c.x && offset.y >= c.y) {
						offset = c;
					}
				}
				
				this._offset = new Point(offset.x, offset.y);
				this._globalOffset = this.getCellPosition(offset.x, offset.y, false);
			}else {
				this._offset = new Point();
				this._globalOffset = new Point();
			}
			
			if (container) {
				this.drawCells(cells, container, absolutePositions);
			}


		}
		
		/**
		 * @inheritDoc
		 */
		public function calculateNearestPosition(point:Point, local:Boolean, result:Position):void{
			if (!point) {
				throw new ArgumentIsNullError("point")
			}
			if (!result) {
				throw new ArgumentIsNullError("result")
			}
			var px:Number = point.x;
			var py:Number = point.y;
			
			if (local) {
				px += this.globalOffset.x;
				py += this.globalOffset.y;
			}
			
			var cx:Number = Math.floor((this.cellWidth * py + this.cellHeight * px) / (this.cellWidth * this.cellHeight));
			var cy:Number = Math.floor((this.cellWidth * py - this.cellHeight * px) / (this.cellWidth * this.cellHeight));
			
			result.x = cx;
			result.y = cy;
		}
		
		/**
		 * @inheritDoc
		 */
		public function calculateCellPosition(x:Number, y:Number, local:Boolean, result:Point):void {
			if (!result) {
				throw new ArgumentIsNullError("result")
			}
			
			var ix:Number = x * this._halfCellWidth - y * this._halfCellWidth;
			var iy:Number = y * this._halfCellHeight + x * this._halfCellHeight;
			
			result.x = ix;
			result.y = iy;
			
			if (local) {
				result.x -= this.globalOffset.x;
				result.y -= this.globalOffset.y;
			}
			
		}
		
		/**
		 * @inheritDoc
		 */
		public function calculateCellPositionAt(position:Position, local:Boolean, result:Point):void {
			if (!position) {
				throw new ArgumentIsNullError("result");
			}
			this.calculateCellPosition(position.x, position.y, local, result);
		}
		
		/**
		 * @inheritDoc
		 */
		public function calculateCellPositionAtPoint(position:Point, local:Boolean, result:Point):void{
			if (!position) {
				throw new ArgumentIsNullError("result");
			}
			this.calculateCellPosition(position.x, position.y, local, result);
		}
		
		/**
		 * @inheritDoc
		 */
		public function getNearestPosition(point:Point, local:Boolean):Position {
			var p:Position = new Position();
			this.calculateNearestPosition(point, local, p)
			return p;
		}
		
		/**
		 * @inheritDoc
		 */
		public function getCellPosition(x:Number, y:Number, local:Boolean):Point {
			var p:Point = new Point();
			this.calculateCellPosition(x, y, local, p)
			return p;
		}
		
		/**
		 * @inheritDoc
		 */
		public function getCellPositionAt(point:Position, local:Boolean):Point {
			return this.getCellPosition(point.x, point.y, local);
		}
		
		/**
		 * @inheritDoc
		 */
		public function getCellPositionAtPoint(point:Point, local:Boolean):Point {
			return this.getCellPosition(point.x, point.y, local);
		}
		
		/**
		 * @inheritDoc
		 */
		public function getRect(rect:Rectangle):Rectangle {
			
			var top:Point = this.getCellPosition(rect.left, rect.top, false);
			var right:Point = this.getCellPosition(rect.right, rect.top, false);
			var bottom:Point = this.getCellPosition(rect.right, rect.bottom, false);
			var left:Point = this.getCellPosition(rect.left, rect.bottom, false);
			
			return new Rectangle(left.x, top.y, right.x - left.x, bottom.y - top.y);
		}
		
		//------------------------------------------------------------------------------------------------
		// Private methods
		//------------------------------------------------------------------------------------------------
		
		private function drawCells(cells:Array, container:Sprite, absolutePositions:Boolean):void {
			
			container.cacheAsBitmap = false;
			
			container.graphics.clear();
			container.graphics.lineStyle(1, 0x00ff00);
			
			for (;container.numChildren > 0; ) {
				container.removeChildAt(0);
			}
			
			for each(var cell:MapNode in cells) {
				
				var p:Point = this.getCellPosition(cell.x, cell.y, !absolutePositions);
				
				container.graphics.moveTo(p.x, p.y);
				container.graphics.lineTo(p.x + this._halfCellWidth, p.y + this._halfCellHeight);
				container.graphics.lineTo(p.x, p.y + this.cellHeight);
				container.graphics.lineTo(p.x - this._halfCellWidth, p.y + this._halfCellHeight);
				container.graphics.lineTo(p.x, p.y);
				
				var tf:TextField = new TextField();
				tf.textColor = 0xffffff;
				tf.x = p.x - 10;
				tf.y = p.y + 8;
				tf.selectable = false;
				tf.text = cell.x + "," + cell.y;
				
				
				container.addChild(tf);
			}
			
			container.cacheAsBitmap = true;
		}
		
		
		
	}
	
}